﻿using System;
using System.Web.UI.WebControls;
using br.com.SistemaChamados.Constants;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Enum;
using br.com.SistemaChamados.Model;
using br.com.SistemaChamados.Model.Common;
using br.com.SistemaChamados.Util;
using System.Web.Security;

public partial class Pages_PersonUpdate : System.Web.UI.Page
{
    private const string SESSION_UPDATE_USER = "userToUpdate";
    private const string SESSION_UPDATE_USER_ID = "UserIdToUpdate";

    private string source = "";

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ViewStateUserKey = Session.SessionID;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        br.com.SistemaChamados.Model.Common.User loggedUser = new br.com.SistemaChamados.Model.Common.User();
        UserController userController = new UserController();
        if (Session[UserConstants.SESSION_USER_LOGGED_IN] != null)
        {
            loggedUser.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN]);
            loggedUser = userController.GetUser(loggedUser);
            this.MasterPageFile = MasterPageDefiner.defineMasterPageByAccessRole(loggedUser.Profile);
            ((Label)Master.FindControl("lblUser")).Text = loggedUser.Name;
            this.Title = "SysCall - Sistema de chamados [logado como " + loggedUser.Name + "]";
        }
        else
        {
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetUserFromSession();
            FillDdlUnit();
            FillData();
            if (!User.IsInRole("ADMIN"))
            {
                ddlRegraAcesso.Items.RemoveAt(ddlRegraAcesso.Items.Count - 1);
            }
        }
    }
    private void FillDdlUnit()
    {
        UnitController unitController = new UnitController();
        ddlUnit.DataSource = unitController.GetUnits();
        ddlUnit.DataTextField = "Name";
        ddlUnit.DataValueField = "Id";
        ddlUnit.DataBind();
        ddlUnit.Items.Insert(0, "Selecione");
    }

    private void GetUserFromSession()
    {
        User user = new User();
        user.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_ID]);
        UserController Controller = new UserController();
        User returnedUser = new User();
        try
        {
            returnedUser = Controller.GetUser(user);
            if (returnedUser != null)
            {
                txbName.Text = returnedUser.Name;
                txbEMail.Text = returnedUser.EMail;
                Session[SESSION_UPDATE_USER] = returnedUser;
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro no carregamento da tela: <br>" + ex.Message +
                               ".');</script>");
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        if (ddlSector.SelectedIndex == 0)
        {
            Response.Write(@"<script language='javascript'>alert('Selecione um setor');</script>");
            ddlSector.Focus();
        }
        else
        {
            if (ddlUnit.SelectedIndex == 0)
            {
                Response.Write(@"<script language='javascript'>alert('Selecione uma unidade');</script>");
                ddlUnit.Focus();
            }
            else
            {
                User updatedUser = new User();
                updatedUser.Sector = new Sector();
                object objectFromSession;
                if (Session[UserConstants.SESSION_USER_ID] != null)
                {
                    objectFromSession = Session[UserConstants.SESSION_USER_ID];
                }
                else
                {
                    objectFromSession = Session[UserConstants.SESSION_USER_LOGGED_IN];
                }
                updatedUser.Id = Convert.ToInt32(objectFromSession);
                Sector sector = new Sector();
                updatedUser.Name = txbName.Text;
                updatedUser.EMail = txbEMail.Text;
                updatedUser.Sector.Id = Convert.ToInt32(ddlSector.SelectedValue);
                updatedUser.Profile = ddlRegraAcesso.SelectedValue.ToString();
                User userFromSession = null;
                if (Session[SESSION_UPDATE_USER] != null)
                {
                    userFromSession = (User)Session[SESSION_UPDATE_USER];
                }
                else
                {
                    string id = Session[UserConstants.SESSION_USER_LOGGED_IN].ToString();
                    UserController userController = new UserController();
                    userFromSession = new User();
                    userFromSession.Id = Convert.ToInt32(id);
                    userFromSession = userController.GetUser(userFromSession);
                }
                if (chbEditPassword.Checked)
                {
                    if (SecurityUtils.createASHA1Hash(txbOldPassword.Text).Equals(userFromSession.Password.Trim()))
                    {
                        updatedUser.Password = txbNewPassword.Text;
                        TryUpdate(updatedUser);
                    }
                    else
                    {
                        Response.Write(@"<script language='javascript'>alert('Senha incorreta !');</script>");
                    }
                }
                else
                {
                    updatedUser.Id = userFromSession.Id;
                    updatedUser.Password = userFromSession.Password;
                    TryUpdate(updatedUser);
                }
            }
        }

    }

    private void TryUpdate(User updatedUser)
    {
        UserController Controller = new UserController();
        try
        {
            if (Controller.UpdateUser(updatedUser) == EnumGenericState.GENERIC_STATE_SUCCESS)
            {
                Response.Write(@"<script language='javascript'>alert('Pessoa Corrigida com Sucesso!');</script>");
                ClearFields();
                if (Session[SESSION_UPDATE_USER] != null)
                {
                    Response.Redirect("UserMain.aspx");
                }
                else
                {
                    Response.Write(@"<script language='javascript'>alert('Será necessária a reinialização da sessão. Você será conduzido novamente à página de login.');</script>");
                    FormsAuthentication.SignOut();
                    Response.Clear();
                    Response.Redirect("~/Pages/Login/Login.aspx");
                }
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante a correção, por favor tente novamente!');</script>");
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro na correção: <br>" + ex.Message +
                               ".');</script>");
            updatedUser = null;
        }
        finally
        { }
    }

    private void ClearSession()
    {
        Session.Remove("id");
        Session.Remove("userToUpdate");
    }

    private void FillData()
    {
        string id = "";
        if (Session[UserConstants.SESSION_USER_ID] == null)
        {
            id = Session[UserConstants.SESSION_USER_LOGGED_IN].ToString();
            this.source = "OWNER";
        }
        else
        {
            id = Session[UserConstants.SESSION_USER_ID].ToString();
            this.source = "OTHER";
        }
        User user = new User();
        UserController userController = new UserController();
        user.Id = Convert.ToInt32(id);
        user = userController.GetUser(user);
        Sector sector = new Sector();
        SectorController sectorController = new SectorController();
        sector.Id = user.Sector.Id;
        sector = sectorController.GetSector(sector);
        try
        {
            MatchDdlUnitValue(sector);
            FillDdlSector();
            MatchDdlSectorValue(sector);
            txbName.Text = Convert.ToString(user.Name);
            txbEMail.Text = Convert.ToString(user.EMail);
            MatchDdlRegraAcesso(user);
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro no carregamento dos valores: <br>" + ex.Message +
                               ".');</script>");
        }
    }

    private void MatchDdlSectorValue(Sector sector)
    {
        ListItem listSector = ddlSector.Items.FindByValue(Convert.ToString(sector.Id));
        for (int i = 0; i < ddlSector.Items.Count; i++)
        {
            ddlSector.Items[i].Selected = false;
        }
        if (listSector != null)
        {
            listSector.Selected = true;
        }
        else
        {
            ddlSector.Items[0].Selected = true;
        }
    }

    private void MatchDdlUnitValue(Sector sector)
    {
        ListItem listUnit = ddlUnit.Items.FindByValue(Convert.ToString(sector.Unit.Id));

        for (int i = 0; i < ddlUnit.Items.Count; i++)
        {
            ddlUnit.Items[i].Selected = false;
        }
        if (listUnit != null)
        {
            listUnit.Selected = true;
        }
        else
        {
            ddlUnit.Items[0].Selected = true;
        }
    }

    private void MatchDdlRegraAcesso(User user)
    {
        ListItem listUserProfile = ddlRegraAcesso.Items.FindByValue(Convert.ToString(user.Profile));

        for (int i = 0; i < ddlRegraAcesso.Items.Count; i++)
        {
            ddlRegraAcesso.Items[i].Selected = false;
        }
        if (listUserProfile != null)
        {
            listUserProfile.Selected = true;
        }
        else
        {
            ddlRegraAcesso.Items[0].Selected = true;
        }
    }

    private void FillDdlSector()
    {
        SectorController sectorController = new SectorController();
        Sector sector = new Sector();
        br.com.SistemaChamados.Model.Unit unit = new br.com.SistemaChamados.Model.Unit();
        if (Convert.ToInt32(ddlUnit.SelectedIndex) != 0)
        {
            unit.Id = Convert.ToInt32(ddlUnit.SelectedValue);
            sector.Unit = unit;
            ddlSector.DataSource = sectorController.ListSectorByUnit(sector);
            ddlSector.DataTextField = "Description";
            ddlSector.DataValueField = "Id";
            ddlSector.DataBind();
            ddlSector.Items.Insert(0, "Selecione");
        }
        else
        {
            ClearDdlSector();
        }
    }

    private void ClearDdlSector()
    {
        for (int i = 0; i < ddlSector.Items.Count; i++)
        {
            ddlSector.Items[i].Selected = false;
        }
        ddlSector.Items[0].Selected = true;
        ddlSector.DataSource = "";
        ddlSector.DataBind();
    }


    private void ClearFields()
    {
        txbName.Text = "";
        txbEMail.Text = "";
        txbNewPassword.Text = "";
        txbPasswordValidate.Text = "";
        txbName.Focus();
    }

    protected void chbEditPassword_CheckedChanged(object sender, EventArgs e)
    {
        if (chbEditPassword.Checked)
        {
            txbNewPassword.Enabled = true;
            txbOldPassword.Enabled = true;
            txbPasswordValidate.Enabled = true;
            passwordValidator.Enabled = true;
            newPasswordValidator.Enabled = true;
            ComparePassword.Enabled = true;
        }
        else
        {
            txbOldPassword.Enabled = false;
            txbNewPassword.Enabled = false;
            txbPasswordValidate.Enabled = false;
            passwordValidator.Enabled = false;
            newPasswordValidator.Enabled = false;
            ComparePassword.Enabled = false;
        }
    }

    protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillDdlSector();
    }
}
